<template>
	<view class="content">
		<!-- 左侧：一级分类列表（垂直可滚动），点击切换当前分类 -->
		<scroll-view scroll-y class="left-aside">
			<!-- flist：一级分类；active 根据 currentId 高亮当前项；tabtap 处理切换 -->
			<view v-for="item in flist" :key="item.id" class="f-item b-b" :class="{active: item.id === currentId}" @click="tabtap(item)">
				{{item.name}}
			</view>
		</scroll-view>
		<!-- 右侧：二级/三级分类区域（联动滚动），支持动画与 scrollTop 定位 -->
		<scroll-view scroll-with-animation scroll-y class="right-aside" @scroll="asideScroll" :scroll-top="tabScrollTop">
			<!-- slist：二级分类；通过 id="main-二级id" 作为锚点用于计算/定位滚动位置 -->
			<view v-for="item in slist" :key="item.id" class="s-list" :id="'main-'+item.id">
				<!-- 二级分类标题（点击跳转到商品列表，展示该二级分类下所有三级商品） -->
				<text class="s-item" @click="navToListSecond(item)">{{item.name}}</text>
				<!-- 三级分类网格列表（tlist 过滤出 pid 等于当前二级分类 id 的项） -->
				<view class="t-list">
					<!-- 点击三级分类跳转到商品列表页，携带 fid/sid/tid 查询参数 -->
					<view @click="navToList(item.id, titem.id)" v-if="titem.pid === item.id" class="t-item" v-for="titem in tlist" :key="titem.id">
						<image :src="titem.picture"></image>
						<text>{{titem.name}}</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				sizeCalcState: false,
				tabScrollTop: 0,
				currentId: 1,
				flist: [],
				slist: [],
				tlist: [],
			}
		},
		onLoad(options){
			// 接收从首页传来的 fid 参数
			if(options.fid){
				this.currentId = Number(options.fid);
				console.log('分类页面接收到分类ID:', this.currentId);
			}
			this.loadData();
		},
		methods: {
			async loadData(){
				try {
					// 调用后端API获取完整三级分类树
					let response = await this.$api.getCategoryTree();

					// 检查响应格式并提取data字段
					if(response.code !== 200 || !response.data){
						throw new Error(response.msg || '获取分类数据失败');
					}

					let list = response.data;

					// 按层级分类：level=0为一级，level=1为二级，level=2为三级
					list.forEach(item=>{
						if(item.level === 0){
							this.flist.push(item);  // 一级分类
						}else if(item.level === 1){
							this.slist.push(item);  // 二级分类
						}else if(item.level === 2){
							this.tlist.push(item);  // 三级分类
						}
					});

					// 设置默认选中第一个一级分类(仅当currentId未设置时)
					if(!this.currentId && this.flist.length > 0){
						this.currentId = this.flist[0].id;
					}
				} catch (error) {
					console.error('加载分类数据失败:', error);
					this.$api.msg('加载分类数据失败');
				}
			},
			//一级分类点击
			tabtap(item){
				if(!this.sizeCalcState){
					this.calcSize();
				}
				
				this.currentId = item.id;
				let index = this.slist.findIndex(sitem=>sitem.pid === item.id);
				this.tabScrollTop = this.slist[index].top;
			},
			//右侧栏滚动
			asideScroll(e){
				if(!this.sizeCalcState){
					this.calcSize();
				}
				let scrollTop = e.detail.scrollTop;
				let tabs = this.slist.filter(item=>item.top <= scrollTop).reverse();
				if(tabs.length > 0){
					this.currentId = tabs[0].pid;
				}
			},
			//计算右侧栏每个tab的高度等信息
			calcSize(){
				let h = 0;
				this.slist.forEach(item=>{
					let view = uni.createSelectorQuery().select("#main-" + item.id);
					view.fields({
						size: true
					}, data => {
						item.top = h;
						h += data.height;
						item.bottom = h;
					}).exec();
				})
				this.sizeCalcState = true;
			},
			navToList(sid, tid){
				uni.navigateTo({
					url: `/pages/product/list?fid=${this.currentId}&sid=${sid}&tid=${tid}`
				})
			}
			,
			navToListSecond(item){
				// 点击二级分类标题，跳转到商品列表，按二级分类聚合
				const sid = item.id
				uni.navigateTo({
					url: `/pages/product/list?fid=${this.currentId}&sid=${sid}`
				})
			}
		}
	}
</script>

<style lang='scss'>
	page,
	.content {
		height: 100%;
		background-color: #f8f8f8;
	}

	.content {
		display: flex;
	}
	.left-aside {
		flex-shrink: 0;
		width: 200upx;
		height: 100%;
		background-color: #fff;
	}
	.f-item {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100upx;
		font-size: 28upx;
		color: $font-color-base;
		position: relative;
		&.active{
			color: $base-color;
			background: #f8f8f8;
			&:before{
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				height: 36upx;
				width: 8upx;
				background-color: $base-color;
				border-radius: 0 4px 4px 0;
				opacity: .8;
			}
		}
	}

	.right-aside{
		flex: 1;
		overflow: hidden;
		padding-left: 20upx;
	}
	.s-item{
		display: flex;
		align-items: center;
		height: 70upx;
		padding-top: 8upx;
		font-size: 28upx;
		color: $font-color-dark;
	}
	.t-list{
		display: flex;
		flex-wrap: wrap;
		width: 100%;
		background: #fff;
		padding-top: 12upx;
		&:after{
			content: '';
			flex: 99;
			height: 0;
		}
	}
	.t-item{
		flex-shrink: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		width: 176upx;
		font-size: 26upx;
		color: #666;
		padding-bottom: 20upx;
		
		image{
			width: 140upx;
			height: 140upx;
		}
	}
</style>